
var express = require('express');
const multer = require('multer');
const xlsx = require("node-xlsx").default;
var router = express.Router();
const path = require("path")
const jwt = require('jsonwebtoken');
const { UserModule } = require('../mongodb/db')
const verifyAuthToken = require('../routes/tokens')
const sendVerificationCode = require('../module/sendVerificationCode')
const bodyParser = require('body-parser');
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});


///////////////////////////////////////////////////////////////////////
//上传图片开始
const storages = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // 文件保存到 uploads 目录
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    cb(null, uniqueSuffix + path.extname(file.originalname)); // 生成唯一文件名
  },
});

// 初始化上传中间件
const uploadss = multer({ storages });

// 文件上传接口
router.post('/xu_uploads', uploadss.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ code: 400, message: '未上传文件' });
  }
  // 返回文件路径
  res.send({
    code: 200,
    message: '上传成功',
    data: {
      filePath: `/uploads/${req.file.filename}`, // 文件访问路径
    },
  });
});

router.post('/putUserHead', async (req, res) => {
  try {
    await BusinessModel.updateOne({ $set: { img1: req.body.head } })
    res.send({
      code: 200,
      message: "修改成功"
    })
  } catch (error) {
    console.log(error);
    res.send({
      code: 500,
      message: '修改失败',
    })
  }
});
//结束

//////////////////////////////////////////////////////////////////////
//支付宝沙箱
const AlipaySdk = require('alipay-sdk').default;
const cors = require('cors');
// const app = express();
const app = express();
app.use(cors({
  origin: 'http://localhost:5173', // 仅允许来自这个源的请求
  credentials: true // 如果需要发送凭证（如 cookies）
}));

app.use(bodyParser.json());

// 初始化支付宝 SDK
const alipaySdk = new AlipaySdk({
  appId: '9021000144618631', // 替换为你的沙箱 AppID
  privateKey: 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC86lEoOrDIiudV2INd2owB0V7vWsCXWTjW2scNi0/b+EGTHj9PitI3Qcznfxqt2TRPpdcOMK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cNV0Lncm04lMcVSVngF3OSUBHJ9mIN34haPStRL+kUwmO3mN/QxMrzMI8qn3ugcV188zQKBgCsopc2vfxNXZiU7BqgNAL35w/elV3Dub1SeWKtaGe9ug/3eKI1ZIgIXJ0mLa5Y9sotkhGzLBcRdjBlnlVugBvJgP68qgswFVJoxztmyPl0CDdLrDxMXgYwYkpfyD/rDaWh1vP0h37s/iKuTvPdanjFCcvLNAZSjxY3AProvZX4hAoGACMWUnt0BFfXnBuIV2aqyxpicL/3df3pIRqd0dudJuISKGUUJUXm3idGT8aPcA0U6l4Z2AquJOjqnbG8EojlTaslnuj9SGVwo3af/ySbnhEqqGVbZfNrx2bS3dulLYZzRGUXXHCxKTuWj1Xw/3ZJUIJvPvcLjypV1254bPNWZkOk=', // 替换为你的私钥
  alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg+zLB2LHHYfOjjLBOi0XUL1Vis49/VD5ZbFMgVhSAo4IAQ/5ArKR6af126MXH21o4iqoniYOBsIVGwPO82qYGv8FXzA1fWzD5A6xRApSL/ssLFnCXCzRrKEk0sU0yV6PCfyKXzv29ZiZ/cKGclk+C/jlIOa/W3U786axLs8mD0wB+HSXdmyjuBf5G6yZnKUYt+FmmY3uCGmdeIhCOnxZ0ud/chlQJPIBY4tfQ6W6vMLpdFEy/9t01s//JQ1btWhsyLF67rXC7x7QAZkckUvEhBprHQgNS4R6WdlVhrj1cOi0SnguLp9FCnGvbbEYH535/82wvIxW0fpWvuY9aUq7zQIDAQAB', // 替换为支付宝返回的公钥
  gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do', // 沙箱环境网关
});

router.get('/createOrder', async (req, res) => {
  const outTradeNo = Date.now().toString(); // 生成订单号
  let qian = req.query.qian
  const amount = qian; // 支付金额（单位：元）
  // const amount = 200
  const result =  alipaySdk.pageExec('alipay.trade.wap.pay', { // 修改为移动端支付接口
      method: 'GET',
      bizContent: {
          out_trade_no: outTradeNo, // 订单号
          product_code: 'QUICK_WAP_WAY', // 修改为移动端支付产品码
          total_amount: amount, // 支付金额
          subject: '余额充值', // 商品名称
          body: '充值', // 商品描述
      },
      return_url: 'http://localhost:5173/money', // 支付成功后的回调地址
      notify_url: 'http://localhost:3000/notify', // 支付结果异步通知地址
  });

  res.send(result);
});

app.listen(3001, () => {
  console.log('Server is running on http://localhost:3001');
});

/////////////////////////////////////////////徐梓鑫后端结束




// 设置文件存储路径和文件名
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // 文件保存到 uploads 目录
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    cb(null, uniqueSuffix + path.extname(file.originalname)); // 生成唯一文件名
  },
});

// 初始化上传中间件
const upload = multer({ storage });

// 文件上传接口
router.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ code: 400, message: '未上传文件' });
  }
  // 返回文件路径
  res.send({
    code: 200,
    message: '上传成功',
    data: {
      filePath: `/uploads/${req.file.filename}`, // 文件访问路径
    },
  });
});

router.post('/putUserHead', async (req, res) => {
  try {
    await UserModule.updateOne({ phone: req.headers.phone }, { $set: { head: req.body.head } })
    res.send({
      code: 200,
      message: "修改成功"
    })
  } catch (error) {
    console.log(error);
    res.send({
      code: 500,
      message: '修改失败',
    })
  }
})
const tencentcloud = require('tencentcloud-sdk-nodejs')
router.post('/faceLogin', async (req, res) => {
  //获取前端传来的base64
  let b64 = req.body.b64
  const IaiClient = tencentcloud.iai.v20200303.Client;
  const clientConfig = {
    credential: {
      //自己的腾讯secretId*****************************
      secretId: "AKIDNaopdFgtsdBVFoAKH8wDScmliSzINejc",
      //自己的腾讯密匙**************************
      secretKey: "kGYdUN7oLhpkR9N6iJkyymNjrqfKm5FF",
    },
    region: "ap-beijing",  //地域参数（华北地区北京）
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };
  const client = new IaiClient(clientConfig);
  const params = {
    "GroupIds": [  //你创建的人员库ID **********************
      "brother"
    ],
    "Image": b64,  //图片的base64格式编码
    "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
    "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
    "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
  };
  let doc = await client.SearchFaces(params)
  //doc为人脸识别后的返回信息
  console.log(doc, 'doc');

  if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
    let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
    //生成token
    let token = jwt.sign({ "name": personName }, "face", { expiresIn: '1d' })
    res.send({
      code: 200,
      msg: "登录成功！",
      token
    })

  } else {
    res.send({
      code: 401,
      msg: '人脸库无此人！'
    })
    return false
  }

})


router.post('/putUser', async (req, res) => {
  try {
    await UserModule.updateOne({ phone: req.headers.phone }, { ...req.body })
    res.send({
      code: 200,
      message: "修改成功"
    })
  } catch (error) {
    console.log(error);
    res.send({
      code: 500,
      message: '修改失败',
    })
  }

})

router.get('/getUserMessage', async (req, res) => {
  let data = await UserModule.find(req.query)
  res.send({
    code: 200,
    msg: '成功',
    data
  })
})


function generateCode() {
  return Math.floor(100000 + Math.random() * 900000).toString();
}


router.post('/getCode', async (req, res) => {
  let phone = req.body.phoneNumber
  console.log(phone);

  let code = generateCode();
  console.log(code);
  try {
    //发送短信
    // await sendVerificationCode(phone, code);
    res.send({ code: 200, phoneCode: code })
  } catch (error) {
    console.log(error);
    res.send({ code: 404 })
  }
})

router.post('/subLogin', async (req, res) => {
  let { phone } = req.body
  try {
    let user = await UserModule.findOne({ phone })
    if (!user) {
      await UserModule.create({ phone, user: `小五${phone}` })
      user = await UserModule.findOne({ phone })
    }

    // 生成 accessToken（有效期 6 小时）
    const accessToken = jwt.sign({ id: user._id }, 'accessToken', { expiresIn: '6h' });

    // 生成 refreshToken（有效期 1 天）
    const refreshToken = jwt.sign({ id: user._id }, 'refreshToken', { expiresIn: '1d' });
    // 生成session
    req.session.user = { phone: user.phone };
    res.send({
      code: 200,
      msg: '登录成功',
      data: {
        accessToken,
        refreshToken,
      }
    })
  } catch (error) {
    res.send({
      code: 404
    })
  }
})
router.post('/passwordLogin', async (req, res) => {
  let { phone, password } = req.body;
  console.log(phone, password);

  // 使用 $and 查询条件确保同时匹配 phone 和 password
  let user = await UserModule.findOne({ phone, password });
  if (user) {
    // 生成 accessToken（有效期 6 小时）
    const accessToken = jwt.sign({ id: user._id }, 'accessToken', { expiresIn: '6h' });

    // 生成 refreshToken（有效期 5 天）
    const refreshToken = jwt.sign({ id: user._id }, 'refreshToken', { expiresIn: '5d' });

    res.send({
      code: 200,
      msg: '登录成功',
      data: {
        accessToken,
        refreshToken
      }
    });
  } else {
    let userPhone = await UserModule.findOne({ phone });
    if (userPhone) {
      res.send({
        code: 404,
        message: '密码错误，请重新输入'
      });
    } else {
      res.send({
        code: 404,
        message: "用户尚未注册"
      });
    }
  }
});

router.get('/userMessage', async (req, res) => {
  console.log(req.headers.phone);

  let { phone } = req.headers
  let data = await UserModule.findOne({ phone })
  res.send({
    code: 200,
    data
  })
})

router.post('/getOldPassword', async (req, res) => {
  let { phone } = req.headers
  let { password } = req.body
  let user = await UserModule.findOne({ phone })
  if (user.password == password) {
    res.send({
      code: 200,
      msg: '密码正确'
    })
  } else {
    res.send({
      code: 404,
      msg: '密码错误'
    })
  }
})

router.post('/putUser', async (req, res) => {
  let { phone } = req.headers
  try {
    await UserModule.updateOne({ phone }, req.body)
    res.send({
      code: 200,
      msg: '修改成功'
    })
  } catch {
    error => {
      res.send({
        code: 404,
        msg: '修改失败'
      })
    }
  }
})
const OpenAI = require('openai');
const axios = require('axios');
const getBotReply = async (message, retries = 3) => {
  
};

// 处理聊天请求
router.post('/chat', async(req, res) => {
  const { message } = req.body;
    try {
        const response = await axios.get(`http://api.qingyunke.com/api.php?key=free&appid=0&msg=${encodeURIComponent(message)}`);
        const reply = response.data.content;
        res.send({ reply });
    } catch (error) {
        console.error('Error fetching chat response:', error);
        res.status(500).json({ error: 'Failed to get chat response' });
    }
});




module.exports = router;